import axios from 'axios'
import useToast from '../hooks/useToast';
import {showLoading,hideLoading} from '../hooks/useLoading'
import { HttpCache,HttpPending,addReqCancel,checkReqAuth,httpRetry } from './helper';
import router from '@/router';
const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  responseType:'json',
  timeout:parseInt(import.meta.env.VITE_HTTP_TIMEOUT),
  withCredentials:true,
})
const HTTP_RETRY=import.meta.env.VITE_HTTP_RETRY=='true'?true:false
const httpPending=new HttpPending()
const httpCache=new HttpCache()
const succCode=[200,0]

instance.interceptors.request.use(function(config){
  if(config.loading){
    showLoading()
  }
  addReqCancel(config)
  checkReqAuth(config)
  httpCache.checkCache(config)
  httpPending.addPending(config)
  return config;
}, function(error){
  return Promise.reject(error);
});

instance.interceptors.response.use(function(response){
  if(response.config.loading){
    hideLoading()
  }
  httpPending.removePending(response.config)
  httpCache.addCache(response) 
  if(succCode.includes(response.data.code)){
    return Promise.resolve(response.data);
  }else{
    let errMsg=response.data.message||response.data.msg;
    useToast(errMsg);
    return Promise.reject(errMsg);
  }
}, async function(error){
  console.warn(error.message)
  if(error.config?.loading||error.message._config?.loading){
    hideLoading()
  }
  httpPending.removePending(error.config)
  if(axios.isCancel(error)&&error.message){
    httpPending.removePending(error.message._config)
    if(error.message._cache&&error.message.data){
      return Promise.resolve(error.message.data)
    }
  }else{
    if(error.response.status==400&&[30203].includes(error.response.data.code)){
      router.replace({
        name:"login",
        query:{
          to:router.currentRoute.value.fullPath
        }
      })
      return
    }
    if(HTTP_RETRY){
      const res=await httpRetry(error.config)
      return Promise.resolve(res)
    }
    useToast(error.message,'error');
  }
  return Promise.reject(error);
});

export default instance

export {
  httpPending,httpCache
}